﻿using KXmlUIControl.KControl;
using KXmlUIControl;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace KWindow.KPageCore
{
    public partial class PageControlBase
    {
        ///////////////////////////////////////////////////////////////////////////////////
        // 组控件的显示逻辑：同一组内的控件同时只能一个被选中，类似于单选框
        // 组名唯一，组的父控件唯一，
        // 同一个组只能有一个父控件，
        // 同一个控件不能作为两个组的父控件
        ///////////////////////////////////////////////////////////////////////////////////

        /// <summary>
        /// 当前所有选中的控件集合
        /// </summary>
        protected List<Control> listCheckedControls = new List<Control>();

        //protected XmlGroupObject SelectedGroup;

        /// <summary>
        /// 组从属关系最大层级数
        /// </summary>
        ///protected int MaxLevel = 0;

        /// <summary>
        /// 根组控件集合(第一级别)
        /// </summary>
        protected Dictionary<string, List<Control>> dicRootGroup = new Dictionary<string, List<Control>>();

        /// <summary>
        /// 从组控件集合(不属于第一级别的从属组合)
        /// </summary>
        protected Dictionary<Control, List<Control>> dicSubGroup = new Dictionary<Control, List<Control>>();

        /// <summary>
        /// 存储所有控件所在组的级别
        /// </summary>
        protected Dictionary<Control, int> dicGroupLevel = new Dictionary<Control, int>();

        /// <summary>
        /// 不同组的父控件可能同时控制一些共享组件
        /// </summary>
        protected List<Control> listSharedGroup = new List<Control>();

        protected void SetDefaultControlCheckedInGroup(string groupName)
        {
            if (Groups != null)
            {
                int index = Groups.FindIndex(r => r.Name.Equals(groupName));
                if (index >= 0)
                {
                    string controlName = Groups[index].Default;
                    if (CheckBoxs != null && CheckBoxs.Count > 0)
                    {
                        int indexCheckBox = CheckBoxs.FindIndex(r => r.Name == controlName);
                        if (indexCheckBox >= 0)
                        {
                            CheckBoxs[indexCheckBox].Checked = true;
                        }
                    }
                }
            }
        }

        protected List<XmlGroupMemberObject> GetXmlGroupMembers(string parent)
        {
            int index = Groups.FindIndex(r => r.Parent.Equals(parent));
            if (index < 0)
            {
                throw new Exception("未知的父控件：" + parent);
            }
            XmlGroupObject group = Groups.Find(r => r.Parent.Equals(parent));
            return group.Controls;
        }

        /// <summary>
        /// 初始化组控件集合
        /// </summary>
        /// <returns></returns>
        protected void InitGroupCtrls()
        {
            dicRootGroup.Clear();
            dicSubGroup.Clear();
            dicGroupLevel.Clear();
            listSharedGroup.Clear();
            for (int i = 0; i < Groups.Count; i++)
            {
                string parentName = Groups[i].Parent;
                List<XmlGroupMemberObject> listMembers = Groups[i].Controls;

                // 首先识别共享组件集合
                if (parentName.Equals("Share"))
                {
                    foreach (XmlGroupMemberObject member in listMembers)
                    {
                        Control child = Controls[member.Name];
                        if (child == null)
                        {
                            throw new Exception("根组成员中包含未知的控件, 名称为:" + member.Name);
                        }
                        listSharedGroup.Add(child);
                    }
                    continue;
                }
                if ((listMembers == null || listMembers.Count == 0) && Groups[i].Depth > 0)
                {
                    Control parentControl = Controls[parentName];
                    if (parentControl == null)
                    {
                        throw new Exception("窗体中包含未知的父节点控件, 名称为:" + Groups[i].Name);
                    }
                    dicSubGroup.Add(parentControl, null);
                    if (!dicGroupLevel.ContainsKey(parentControl))
                    {
                        dicGroupLevel.Add(parentControl, Groups[i].Depth);
                    }
                    else
                    {
                        int nv = dicGroupLevel[parentControl];
                        dicGroupLevel[parentControl] = (Groups[i].Depth < nv ? Groups[i].Depth : nv);
                    }
                    continue;
                }
                //if (string.IsNullOrEmpty(parentName))
                //{
                //    throw new Exception("组的从属父节点为空, 组名称为:" + Groups[i].GroupName);
                //}
                // 根组
                if (Groups[i].Depth == 0 || parentName.Equals("root"))
                {
                    List<Control> listChilds = new List<Control>();
                    foreach (XmlGroupMemberObject member in listMembers)
                    {
                        Control child = Controls[member.Name];
                        if (child == null)
                        {
                            throw new Exception("根组成员中包含未知的控件, 名称为:" + member.Name);
                        }
                        listChilds.Add(child);
                        if (!dicGroupLevel.ContainsKey(child))
                        {
                            dicGroupLevel.Add(child, member.Level);
                        }
                        else
                        {
                            dicGroupLevel[child] = (member.Level < dicGroupLevel[child] ? member.Level : dicGroupLevel[child]);
                        }
                    }
                    dicRootGroup.Add(Groups[i].Name, listChilds);
                    continue;
                }
                else if (Groups[i].Depth > 0)
                {
                    Control parentControl = Controls[parentName];
                    if (parentControl == null)
                    {
                        throw new Exception("窗体中包含未知的父节点控件, 名称为:" + Groups[i].Name);
                    }
                    List<Control> listChilds = new List<Control>();
                    foreach (XmlGroupMemberObject member in listMembers)
                    {
                        Control child = Controls[member.Name];
                        if (child == null)
                        {
                            throw new Exception("组成员中包含未知的控件, 名称为:" + member.Name);
                        }
                        listChilds.Add(child);
                        if (!dicGroupLevel.ContainsKey(child))
                        {
                            dicGroupLevel.Add(child, member.Level);
                        }
                        else
                        {
                            dicGroupLevel[child] = (member.Level < dicGroupLevel[child] ? member.Level : dicGroupLevel[child]);
                        }
                    }
                    dicSubGroup.Add(parentControl, listChilds);
                    continue;
                }
            }
        }

        private void ShowRootGroupCtrls()
        {
            foreach (List<Control> list in dicRootGroup.Values)
            {
                list.ForEach(r => r.Visible = true);
            }
            foreach (List<Control> list in dicSubGroup.Values)
            {
                if (list != null)
                {
                    list.ForEach(r => r.Visible = false);
                }
            }
        }

        protected bool IsRootGroupControl(Control ctl)
        {
            foreach (List<Control> list in dicRootGroup.Values)
            {
                if (list.Contains(ctl))
                {
                    return true;
                }
            }
            return false;
        }

        /// <summary>
        /// 找到位于同一组的其它控件
        /// </summary>
        /// <param name="ctl">当前选中的控件</param>
        /// <returns></returns>
        protected List<Control> GetGroupBrotherControl(Control ctl)
        {
            if (!dicGroupLevel.ContainsKey(ctl))
            {
                throw new Exception("级数字典中包含未知的控件, 名称为:" + ctl.Name);
            }
            List<Control> listBrothers = new List<Control>();

            // 从根控件组查找
            if (dicGroupLevel[ctl] == 0 && IsRootGroupControl(ctl))
            {
                foreach (List<Control> list in dicRootGroup.Values)
                {
                    if (list.Contains(ctl))
                    {
                        listBrothers.AddRange(list);
                        listBrothers.Remove(ctl);
                        return listBrothers;
                    }
                }
                return listBrothers;
            }

            // 从非根组中查找
            foreach (KeyValuePair<Control, List<Control>> pair in dicSubGroup)
            {
                Control key = pair.Key;
                List<Control> list = pair.Value;
                if (list == null)
                {
                    continue;
                }
                if (listCheckedControls.Contains(key) && list.Contains(ctl))
                {
                    listBrothers.AddRange(list);
                    listBrothers.Remove(ctl);
                    return listBrothers;
                }
            }
            return listBrothers;
        }

        protected virtual void CheckBox_CheckedChanged(object sender, EventArgs e)
        {
            if (sender is KCheckBox)
            {
                KCheckBox box = sender as KCheckBox;
                if (box.Checked)
                {
                    OnCheckBoxChecked(box);
                }
                else
                {
                    OnCheckBoxUnChecked(box);
                }
            }
        }

        protected void CheckOtherShareCheckBox(Control control)
        {
            if (!listSharedGroup.Contains(control))
            {
                return;
            }
            foreach (Control sharedControl in listSharedGroup)
            {
                if (sharedControl == control)
                {
                    continue;
                }
                if (sharedControl is KCheckBox)
                {
                    KCheckBox box = sharedControl as KCheckBox;
                    if (box.Checked)
                    {
                        OnCheckBoxChecked(sharedControl);
                    }
                }
            }
        }

        protected void OnCheckBoxChecked(Control control)
        {
            if (!listCheckedControls.Contains(control))
            {
                listCheckedControls.Add(control);
            }
            SetBrotherControlCheckedStatus(control);
            if (dicSubGroup.ContainsKey(control))
            {
                SetGroupMemberValue(control, true);
            }
        }

        protected void OnCheckBoxUnChecked(Control control)
        {
            if (listCheckedControls.Contains(control))
            {
                listCheckedControls.Remove(control);
            }
            if (dicSubGroup.ContainsKey(control))
            {
                SetGroupMemberValue(control, false);
            }

            // 假如是共享组件, 需要处理设置其他共享组件的状态
            if (listSharedGroup.Contains(control))
            {
                CheckOtherShareCheckBox(control);
            }
        }

        protected void SetBrotherControlCheckedStatus(Control control)
        {
            List<Control> listBrothers = GetGroupBrotherControl(control);
            for (int i = 0; i < listBrothers.Count; i++)
            {
                Control brother = listBrothers[i];
                if (brother is KCheckBox)
                {
                    KCheckBox box = brother as KCheckBox;
                    box.Checked = false;
                }
            }
        }

        /// <summary>
        /// 设置组内成员控件的值
        /// 如果组当前为选中状态，则设置默认成员为选中
        /// 如果组当前为未选中状态，则设置所有成员为未选中（同时对用户隐藏）
        /// </summary>
        /// <param name="parentControl">组的父控件</param>
        /// <param name="groupChecked">组当前是否被选中</param>
        protected void SetGroupMemberValue(Control parentControl, bool groupChecked)
        {
            List<Control> listMembers = dicSubGroup[parentControl];
            XmlGroupObject group = Groups.Find(r => r.Parent.Equals(parentControl.Name));
            List<XmlGroupMemberObject> listConfig = GetXmlGroupMembers(parentControl.Name);
            if (string.IsNullOrEmpty(group.Name))
            {
                throw new Exception("配置中未找到指定组, 其父控件名称为:" + parentControl.Name);
            }
            if (listMembers == null)
            {
                return;
            }
            for (int i = 0; i < listMembers.Count; i++)
            {
                Control child = listMembers[i];
                child.Visible = groupChecked;
                XmlGroupMemberObject config = listConfig.Find(r => r.Name.Equals(child.Name));
                if (string.IsNullOrEmpty(config.Name))
                {
                    throw new Exception("组配置中未找到指定控件, 名称为:" + child.Name);
                }
                if (groupChecked)
                {
                    config.SetControlValue(child);
                }
                if (child is KCheckBox)
                {
                    KCheckBox cb = child as KCheckBox;
                    if (cb.Name.Equals(group.Default) && groupChecked)
                    {
                        cb.Checked = true;
                    }
                    else
                    {
                        cb.Checked = false;
                    }
                    cb.Visible = groupChecked;
                }
            }
        }
    }
}
